package com.apes.fico.masterdata.gl.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.fico.masterdata.gl.model.AccountingSystem;
import com.apes.fico.masterdata.gl.respository.AccountingSystemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @ClassName AccountingSystem
 * @Description TODO
 * @Author pengyb
 * @Date 2018/12/24 11:53
 * @Version 1.0
 **/
@Service("accountingSystemService")
public class AccountingSystemService extends DomainService {
    @Autowired
    private AccountingSystemRepository accountingSystemRepository;

    /**
     * 保存
     * @param request
     * @return
     */
    public AccountingSystem save(SimpleRequest request){
        AccountingSystem accountingSystem=request.getO(AccountingSystem.class);
        accountingSystem.setCreateDate(new Date());
        return accountingSystemRepository.saveAndFlush(accountingSystem);
    }

    /**
     * 修改
     * @param request
     * @return
     */
    public AccountingSystem update(SimpleRequest request){
        checkData(request);
        AccountingSystem accountingSystem=request.getO(AccountingSystem.class);
        accountingSystem.setUpdateDate(new Date());
        return  accountingSystemRepository.saveAndFlush(accountingSystem);
    }

    /**
     * 删除
     * @param request
     * @return
     */
    public String delete(SimpleRequest request){
        checkData(request);
        AccountingSystem accountingSystem=request.getO(AccountingSystem.class);
        accountingSystemRepository.delete(accountingSystem.getId());
        return "删除成功！";
    }

    /**
     * 检查
     * @param request
     */
    public void checkData(SimpleRequest request){
        AccountingSystem accountingSystem=accountingSystemRepository.findOne((String) request.get("id"));
        if(accountingSystem==null) throw new RuntimeException("科目"+accountingSystem.getId()+"不存在");
        if (accountingSystem.getVersion()!=(int)request.get("version"))throw new RuntimeException("科目"+accountingSystem.getId()+"已更新或已删除");
    }

    /**
     * 下拉模糊查询使用
     * @param request
     * @return
     */
    public Page<AccountingSystem> find(SimpleRequest request){
        return accountingSystemRepository.find(request.get("key"),PageRequest.of(request.get("page"),request.get("size")));
    }
}
